package com.ybkj.daijia.server.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.server.event.model.ActivityReturnEvent;
import com.ybkj.daijia.server.event.model.MemberNoticeEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.MemberNotice;
import com.ybkj.daijia.server.model.NoticeXPassenger;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.sales.Activity;
import com.ybkj.daijia.server.sales.Activity.ActivityType;
import com.ybkj.daijia.server.sales.ActivityCouponRule;
import com.ybkj.daijia.server.sales.ActivityVo;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.ActivityService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.MemberNoticeService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.NoticeXPassengerService;
import com.ybkj.daijia.server.service.SmsService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ActivityReturnEventListener implements ApplicationListener<ActivityReturnEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ActivityReturnEventListener.class);

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MemberNoticeService memberNoticeService;

    @Autowired
    private NoticeXPassengerService noticeXPassengerService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private CouponRuleService couponRuleService;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private MemberService memberService;

    @Override
    @Async
    public void onApplicationEvent(ActivityReturnEvent event) {
        logger.debug("member ActivityReturnEvent event:{}", "");

        Activity activity = (Activity) event.getSource();
        ActivityVo activityVo = event.getActivityVo();
        String memo = event.getMemo();
        Passenger passenger = event.getPassenger();
        String messageType = activity.getMessageType();

        Company passengerCompany = companyService.findOne(passenger.getCompanyId());
        Company finalCompany = passengerCompany;
        Company main = companyService.getMain();
        Setting setting = settingUtils.get();
        if (!main.getId().equals(passengerCompany.getId()) && setting.isSmsMainCompany()) {
            finalCompany = main;
        }
        if (messageType != null) {
            if (messageType.contains("sms")) {
                try {
                    if (activity.getActivityType().equals(ActivityType.cash)) {
                        SmsTemplet templet = smsService
                            .findByAlias(finalCompany.getId(), SmsType.activity);
                        if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                            Passenger findOnePassenger = memberService
                                .findOnePassenger(passenger.getId());
                            double doubleValue = findOnePassenger.getDrawMoney()
                                .add(findOnePassenger.getNodrawMoney())
                                .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            //smsService.sendSms(passenger.getPhone(), "activity", "{\"活动名称\":\""+activity.getActivityEventName()+"\",\"返现金额\":\""+activity.getMoney()+"\",\"余额\":\""+doubleValue+"\",\"投诉建议电话\":\""+finalCompany.getTelephone()+"\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                            //短信发送（改）
                            JSONObject smsParam = new JSONObject();
                            smsParam.put("money", activity.getMoney());
                            smsParam.put("balance", doubleValue);
                            smsParam.put("tel", finalCompany.getTelephone());
                            smsService.sendSms(passenger.getPhone(), templet.getTemplateId(),
                                smsParam.toJSONString(), finalCompany.getId(), 0,
                                finalCompany.getSignName());
                        }
                    } else if (activity.getActivityType().equals(ActivityType.coupon)) {
                        SmsTemplet templet = smsService
                            .findByAlias(finalCompany.getId(), SmsType.activityCoupon);
                        if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                            Result<ActivityCouponRule> result = salesApi
                                .findByActivity(activity.getId());
                            List<ActivityCouponRule> list = result.getData();
                            String content = "";

                            List<Long> couponIds = activityVo.getCouponIds();
                            List<Integer> couponAmounts = activityVo.getCouponAmounts();

                            if (!CollectionUtils.isEmpty(couponIds)) {
                                for (int i = 0; i < couponIds.size(); i++) {
                                    CouponRule couponRule = couponRuleService
                                        .findOne(Long.valueOf(couponIds.get(i)));
                                    Integer amount = Integer.valueOf(couponAmounts.get(i));
                                    if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                                        content += "【" + couponRule.getTitle() + "】券:";
                                        content += amount + "张 :";
                                        content += couponRule.getMoney() + "元";
                                    } else if (couponRule.getType()
                                        .equals(CouponRule.TYPE_DISCOUNT)) {
                                        content += "【" + couponRule.getTitle() + "】券:";
                                        content += amount + "张 :";
                                        content += couponRule.getDiscount() + "折";
                                    }
                                }
                            }
                            //smsService.sendSms(passenger.getPhone(), "activityCoupon", "{\"活动名称\":\""+activity.getActivityEventName()+"\",\"优惠券名称\":\""+content+"\",\"投诉建议电话\":\""+finalCompany.getTelephone()+"\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                            //短信发送（改）
                            JSONObject smsParam = new JSONObject();
                            smsParam.put("name", content);
                            smsParam.put("tel", finalCompany.getTelephone());
                            smsService.sendSms(passenger.getPhone(), templet.getTemplateId(),
                                smsParam.toJSONString(), finalCompany.getId(), 0,
                                finalCompany.getSignName());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (messageType.contains("message")) {
                try {
                    MemberNotice memberNotice = new MemberNotice();
                    memberNotice.setCompanyId(passengerCompany.getId());
                    memberNotice.setContent(memo);
                    memberNotice.setOperating("系统");
                    memberNotice.setPassengerIds("," + passenger.getId() + ",");
                    memberNoticeService.insertRecord(memberNotice);

                    NoticeXPassenger noticeXPassenger = new NoticeXPassenger();
                    noticeXPassenger.setPassengerId(passenger.getId());
                    noticeXPassenger.setNoticeId(memberNotice.getId());
                    noticeXPassenger.setHasRead(false);
                    noticeXPassengerService.save(noticeXPassenger);

                    List<Passenger> passengerList = new ArrayList<Passenger>();
                    passengerList.add(passenger);

                    MemberNoticeEvent memberNoticeEvent = new MemberNoticeEvent(memberNotice,
                        passengerList);
                    applicationEventMulticaster.multicastEvent(memberNoticeEvent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
